﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Diagnostics;

namespace Projekt
{
    public partial class introduceBill : Form
    {
        Dalgen conn = Dalgen.Instance;
        private Bill fakt = Bill.Instance;
        private Unit units = new Unit();
        private DataTable firmList;
        private int activeDateField = 0;
        private DataTable unitList;
        private int editmode;
        public introduceBill()
        {
            if (fakt != null)
            {
                InitializeComponent();
                firmlistRefresh();
                goodsReceivedNoteNr.Text = fakt.getRecNr().ToString();
                billDate.Text = Calendar.SelectionStart.ToShortDateString();
                goodsReceivedNoteDate.Text = Calendar.SelectionStart.ToShortDateString();
                unitList = units.getUnitList();
                produceUM.DataSource = unitList;
                produceUM.DisplayMember = "MNev";
                editmode = 0;
            }
            else { this.Close(); }
        }

        public introduceBill(string nirNr)
        {

            if (fakt != null)
            {

                InitializeComponent();
                editmode = 1;
                grn grn = new grn();
                firmlistRefresh();
                supplierSelect.Visible = false;
                supplierLabel.Visible = false;
                addSuplier.Visible = false;
                supplierName.Text = fakt.getSupplierName(nirNr);
                supplierCUI.Text = fakt.getSupplierCui(nirNr);
                billNr.Text = fakt.getBillnr(nirNr);
                goodsReceivedNoteNr.Text = nirNr;
		        billDate.Text = fakt.getBillDate(nirNr);
                supplierBankAccount.Text = fakt.getBancAccount(nirNr);
                goodsReceivedNoteDate.Text = grn.getGRNDate(nirNr);
                unitList = units.getUnitList();
                produceUM.DataSource = unitList;
                produceUM.DisplayMember = "MNev";
                DataTable dt = fakt.getNirlines(nirNr);
                nirLines.Rows.Add(dt.Rows.Count);
                int line = 0;
                foreach (DataRow rows in dt.Rows)
                {
                    for (int i = 0; i < rows.Table.Columns.Count; i++ )
                    {
                        nirLines.Rows[line].Cells[i].Value = rows[i];
                    }
                    line++;
                    
                }
            }
            else
            {
                this.Close();
            }
        }

        public bool accesible()
        {
            return fakt != null;
        }
        /***************************************\
        |           Input Validating:           |
        |                                       |
        |Quantity: Only numbers allowed         |
        |Prize: Only numbers allowed            |
        |Sell prize: Only numbers allowed       |
        \***************************************/

        private void nirLines_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            DataGridViewTextBoxCell cell = nirLines[e.ColumnIndex, e.RowIndex] as DataGridViewTextBoxCell;
            if (cell != null && e.ColumnIndex!=0)
            {
                String cellValue = e.FormattedValue.ToString();
                if (cellValue != "")
                {
                    try
                    {
                        double tmp;
                        if (!double.TryParse(cellValue, out tmp)) 
                        { 
                            e.Cancel = true;
                            MessageBox.Show("Only numbers allowed");
                        }
                    }
                    catch (Exception) { e.Cancel = true; }
                }
            }
        }

        private void firmlistRefresh()
        {
            try
            {
                Firm ceg = new Firm();
                firmList = ceg.getFirmList();
                supplierSelect.DataSource = firmList;
                supplierSelect.DisplayMember = "CNev";
            }
            catch (Exception e) { MessageBox.Show(e.ToString()); }
        }

        private void introduceBill_Load(object sender, EventArgs e)
        {

        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                DataRow temp = firmList.Rows[supplierSelect.SelectedIndex];
                supplierName.Text = temp[1].ToString();
                supplierCUI.Text = temp[0].ToString();
                billDataPanel.Visible = true;
            }
            catch (Exception es) { MessageBox.Show(es.ToString()); }

        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void calendarBoxImage_Click(object sender, EventArgs e)
        {
            try
            {
                Calendar.Visible = true;
                activeDateField = 1;
            }
            catch (Exception es) { MessageBox.Show(es.ToString()); }
        }

        private void Calendar_DateChanged(object sender, DateRangeEventArgs e)
        {
            try
            {
                Calendar.Visible = false;
                if (activeDateField == 1) billDate.Text = Calendar.SelectionStart.ToShortDateString();
                else goodsReceivedNoteDate.Text = Calendar.SelectionStart.ToShortDateString();
            }
            catch (Exception es) { MessageBox.Show(es.ToString()); }
        }

        public static void addSuplierThread()
        {
            try
            {
                Application.Run(new new_firm());
                Application.ExitThread();
            }
            catch (Exception es) { MessageBox.Show(es.ToString()); }
        }

        private void addSuplier_Click(object sender, EventArgs e)
        {
            try
            {
                int ThreadNr = Process.GetCurrentProcess().Threads.Count;
                System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(addSuplierThread));
                t.Start();
                while (Process.GetCurrentProcess().Threads.Count != ThreadNr) { Thread.Sleep(1000); }
                firmlistRefresh();
            }
            catch (Exception es) { MessageBox.Show(es.ToString()); }
        }

        private void goodsReceivedNoteDatePicture_Click(object sender, EventArgs e)
        {
            try
            {
                Calendar.Visible = true;
                activeDateField = 2;
            }
            catch (Exception es) { MessageBox.Show(es.ToString()); }
        }

        private void goodsReceivedNotePanel_Enter(object sender, EventArgs e)
        {

        }

        private void Save_Click(object sender, EventArgs e)
        {
            try
            {
                if (billNr.Text == "" || billDate.Text == "" || goodsReceivedNoteDate.Text == "") MessageBox.Show("Blank input box not allowed");
                else
                {
                    int db = 0;
                    bool ok = true;
                    DataTable tmp = new DataTable();
                    tmp.Columns.Add("produceName");
                    tmp.Columns.Add("produceUM");
                    tmp.Columns.Add("produceQuantity");
                    tmp.Columns.Add("producePrize");
                    tmp.Columns.Add("produceSellPrize");
                    string[] tmprow = new string[5];


                    foreach (DataGridViewRow row in nirLines.Rows)
                    {
                        if (row.Cells[0].Value != null)
                        {
                            int index = -1;
                            foreach (DataGridViewCell cell in row.Cells)
                            {
                                index++;
                                if (cell.Value == null) ok = false;
                                else tmprow.SetValue(cell.Value.ToString(), index);
                            }
                            if (ok) tmp.Rows.Add(tmprow.ToArray());
                            //if (db > 6 || (db == 6 && nirLines.Rows.Count == 1))
                            else
                            {
                                MessageBox.Show("Blank input box not allowed");
                                ok = false;
                                break;
                            }
                        }
                    }
                    if (ok)
                    {
                        if (editmode == 1)
                        {
                            conn.deleteNir(goodsReceivedNoteNr.Text);
                        }
                        fakt.addBill(supplierCUI.Text, billNr.Text, billDate.Text, supplierBankAccount.Text, tmp, goodsReceivedNoteNr.Text, goodsReceivedNoteDate.Text);
                        Form bon = new newGrn(tmp, goodsReceivedNoteNr.Text, goodsReceivedNoteDate.Text);
                        bon.Show();
                        this.Close();
                    }
                }
            }
            catch (Exception es) { MessageBox.Show(es.ToString()); }
        }

        private void nirLines_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (editmode == 0)
                {
                    if (e.RowIndex >= 0)
                    {
                        if (e.ColumnIndex == 3)
                        {
                            int sor = nirLines.CurrentRow.Index;
                            //  Int32 sor = nirLines.Rows.GetRowCount(DataGridViewElementStates.Selected);
                            if (nirLines.Rows[sor].Cells[3].Value.ToString().Length > 0)
                                nirLines.Rows[sor].Cells[4].Value = (Math.Round(Convert.ToDouble((nirLines.Rows[sor].Cells[3].Value.ToString())) * 1.24, 2)).ToString();

                        }
                    }
                }
            }
            catch (Exception es) { MessageBox.Show(es.ToString()); }
        }

        private void introduceBill_Closing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = false;
            fakt = Bill.disposeInstance;
        }

        private void billDataPanel_Enter(object sender, EventArgs e)
        {

        }
    }
}
